﻿using Photon.SocketServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExitGames.Logging;
using LitJson;
using TaiDouCommon;
using TaiDouCommon.Model;
using TaiDouPhotonServer;
using TaiDouPhotonServer.DB.Manager;
using TaiDouPhotonServer.Tools;

namespace TaiDouPhotonServer.Handlers
{

    //登陆协议处理
    class LoginHandler:HandlerBase
    {
        private static readonly ILogger log = LogManager.GetCurrentClassLogger();

        private UserManager userManager;

        public LoginHandler()
        {
            userManager = new UserManager();
        }

        public override OperationCode OpCode {
            get {
                return OperationCode.Login;
            }
        }
        public override OperationResponse OnHandleMessage(OperationRequest request, ClientPeer peer)
        {
            OperationResponse response = new OperationResponse(request.OperationCode);

            Dictionary<byte, object> parameters = request.Parameters;
            object jsonObj = null;
            parameters.TryGetValue((byte) ParameterCode.User, out jsonObj);
            if (jsonObj != null)
            {
                User user = JsonMapper.ToObject<User>(jsonObj.ToString());

                //查询数据库中是否存在该用户
                User userDB = userManager.GetUserByUsername(user.UserName);
                if (userDB != null)
                {
                    //校验密码是否一致
                    log.Debug("userDB.Password=" + userDB.Password + " user.Password=" + MD5Tool.Md5Hash(user.Password));
                    if (userDB.Password == MD5Tool.Md5Hash(user.Password))
                    {
                        response.ReturnCode = (short)ReturnCode.Succ;
                        peer.loginUser = userDB;
                    }
                    else
                    {
                        response.ReturnCode = (short)ReturnCode.Fail;
                        response.DebugMessage = "密码错误";
                    }
                }
                else
                {
                    response.ReturnCode = (short)ReturnCode.Fail;
                    response.DebugMessage = "用户不存在";
                }
            }

            return response;
        }
    }
}
